package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.WeiPayConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SiyuRecharge;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISiyuRechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值记录Controller
 */
@RestController
@RequestMapping("/system/recharge")
public class SiyuRechargeController extends BaseController {

    @Autowired
    private ISiyuRechargeService siyuRechargeService;

    /**
     * 查询充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:list')")
    @GetMapping("/list")
    public TableDataInfo list(SiyuRecharge siyuRecharge) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!user.isAdmin()) {
            siyuRecharge.setUserId(user.getUserId());
        }
        startPage();
        List<SiyuRecharge> list = siyuRechargeService.selectSiyuRechargeList(siyuRecharge);
        return getDataTable(list);
    }

    /**
     * 新增充值记录
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:add')")
    @Log(title = "充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SiyuRecharge siyuRecharge) {
        return toAjax(siyuRechargeService.insertSiyuRecharge(siyuRecharge));
    }

    /**
     * 新增支付订单
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:addpay')")
    @Log(title = "申请支付订单", businessType = BusinessType.INSERT)
    @PostMapping("/applyPayOrder")
    public AjaxResult applyPayOrder(@RequestBody SiyuRecharge payOrder) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        payOrder.setOutTradeNo("TQTZ" + IdUtils.fastSimpleUUID().substring(0, 12).toUpperCase());
        payOrder.setUserId(userId);
        payOrder.setRechargeType("自助充值");
        HashMap<String, String> data = new HashMap<>();
        data.put("body", userId + "天启探知充值"); //商品描述
        data.put("out_trade_no", payOrder.getOutTradeNo()); //使用当前用户订单的编号作为当前支付交易的交易号
        data.put("fee_type", "CNY"); //支付币种
        BigDecimal totalFee = payOrder.getTotalFee();
        data.put("total_fee", String.valueOf(totalFee.multiply(new BigDecimal(100)).intValue())); //支付额
        data.put("trade_type", "NATIVE"); //交易类型
        data.put("attach", userId.toString()); //交易类型
        data.put("notify_url", "http://175.178.170.139:8093/system/recharge/payNotify"); //设置支付完成时的回调方法法接口
        WXPay wxPay = new WXPay(new WeiPayConfig());
        Map<String, String> resp; //发送请求
        try {
            resp = wxPay.unifiedOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
            return error("支付异常");
        }
        payOrder.setStatus("0");    //0：未启用
        siyuRechargeService.insertSiyuRecharge(payOrder);
        JSONObject reJsson = new JSONObject();
        reJsson.put("payUrl", resp.get("code_url"));
        reJsson.put("outTradeNo", payOrder.getOutTradeNo());
        reJsson.put("totalTee", totalFee);
        return success(reJsson);
//        return success( JSONObject.parseObject(" {\n" +
//                "\"payUrl\": \"weixin://wxpay/bizpayurl?pr=IuTwJK4z3\",\n" +
//                "\"outTradeNo\": \"TQTZ6500B0154DCA\",\n" +
//                "\"totalTee\": 800\n" +
//                "}"));
    }

    /**
     * 回调(修改支付订单)
     */
    @Anonymous
    @PostMapping("/payNotify")
    public String payNotify(HttpServletRequest request) throws Exception {
        // 1.接收微信支付平台传递的数据（使用request的输入流接收）
        ServletInputStream is = request.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        StringBuilder builder = new StringBuilder();
        while ((len = is.read(bs)) != -1) {
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        //使用帮助类将xml接口的字符串装换成map
        Map<String, String> map = WXPayUtil.xmlToMap(s);
        if (map != null && "success".equalsIgnoreCase(map.get("result_code"))) { //支付成功
            //2.修改订单状态为 已支付 充值
            int success = siyuRechargeService.updatePayOrderStatus(map);
            //3.响应微信支付平台
            if (success == 2) {
                HashMap<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("appid", map.get("appid"));
                resp.put("result_code", "success");
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }

    /**
     * 轮询支付订单
     */
    @GetMapping(value = "/lunxun/{outTradeNo}")
    public AjaxResult getInfo(@PathVariable("outTradeNo") String outTradeNo) {
        SiyuRecharge siyuRecharge = siyuRechargeService.selectSiyuRechargeList(new SiyuRecharge(outTradeNo)).get(0);
        if (siyuRecharge != null && "1".contains(siyuRecharge.getStatus())) {
            return success("ok");
        } else {
            return success("no");
        }
    }

    /**
     * 导出充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:export')")
    @Log(title = "充值记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SiyuRecharge siyuRecharge) {
        List<SiyuRecharge> list = siyuRechargeService.selectSiyuRechargeList(siyuRecharge);
        ExcelUtil<SiyuRecharge> util = new ExcelUtil<SiyuRecharge>(SiyuRecharge.class);
        util.exportExcel(response, list, "充值记录数据");
    }

}
